import { NavBar, DatePicker, Tabs } from 'antd-mobile'
import { useEffect, useMemo, useState } from 'react'
import classNames from 'classnames'
import dayjs from 'dayjs'
import { useSelector } from 'react-redux'
import { groupBy } from 'lodash'
import ReactEcharts from 'echarts-for-react'
import { billTypeToName } from '@/contants/index'

const Year = () => {
  // 按月做数据的分组
  const { billList } = useSelector(state => state.bill)
  const billGroup = useMemo(() => {
    return groupBy(billList, (item) => dayjs(item.date).format('YYYY'))
  }, [billList])
  // 控制弹框的打开和关闭
  const [dataVisible, setDataVisible] = useState(false)
  // 控制时间显示
  const [currentDate, setCurrentDate] = useState(() => {
    return dayjs(new Date()).format('YYYY')
  })

  // 初始化的时候把当前年的统计数据显示出来
  useEffect(() => {
    onConfirm(currentDate)
  }, [])
  const [currentMothList, setMonthList] = useState([])
  const monthResult = useMemo(() => {
    //支出  收入  结余
    let pay = 0
    let income = 0
    if (currentMothList) {
      pay = currentMothList.filter(item => item.type === 'pay').reduce((pre, now) => pre + now.money, 0)
      income = currentMothList.filter(item => item.type === 'income').reduce((pre, now) => pre + now.money, 0)
    }

    return {
      pay,
      income,
      total: pay + income
    }
  }, [currentMothList])

  // 确认回调
  const onConfirm = (date) => {
    setDataVisible(false)
    // 其他逻辑
    const formatDate = dayjs(date).format('YYYY')
    setCurrentDate(formatDate);
    setMonthList(billGroup[formatDate])
  }
  // 当前年按照月来做分组
  const monthGroup = useMemo(() => {
    const groupDate = groupBy(currentMothList, (item) => dayjs(item.date).format('YYYY-MM'))
    const keys = Object.keys(groupDate)
    return {
      groupDate,
      keys
    }
  }, [currentMothList])
  const _groupDate = monthGroup.groupDate
  // 定义两个数组存储饼状图所需的数据
  const payData = []
  const incomeData = []
  const [classType, setClassType] = useState('pay')
  //将收支按照类别进行统计
  const classGroup = () => {
    for (let key in _groupDate) {
      _groupDate[key].map((item) => {
        // 处理数据，图形结合
        if (item.type === 'pay') {
          let find = payData.find(element => element.name === billTypeToName[item.useFor])
          if (find) {
            find.value += Math.abs(item.money)
          } else {
            payData.push({ value: Math.abs(item.money), name: billTypeToName[item.useFor] })
          }
        } else {
          let find = incomeData.find(element => element.name === billTypeToName[item.useFor])
          if (find) {
            find.value += item.money
          } else {
            incomeData.push({ value: item.money, name: billTypeToName[item.useFor] })
          }
        }
      })
    }
  }
  classGroup()

  // 绘制图表
  const getoption = () => {
    // 饼状图
    let pieOption = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '0',
        left: 'center'
      },
      series: [
        {
          name: classType === 'pay' ? '支出' : '收入',
          type: 'pie',
          top: '10%',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: classType === 'income' ? incomeData : payData
        }
      ]
    };

    // 数据处理柱状图可识别的形式
    const payName = []
    payData.map(index => {
      if (index.value) payName.push(index.name)
    })
    const payValue = []
    payData.map(index => {
      if (index.value) payValue.push(index.value)
    })
    const incomeName = []
    incomeData.map(index => {
      incomeName.push(index.name)
    })
    const incomeValue = []
    incomeData.map(index => {
      incomeValue.push(index.value)
    })
    // 柱状图
    let barOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: classType === 'income' ? incomeName : payName,
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: 'Direct',
          barWidth: '60%',
          data: classType === 'income' ? incomeValue : payValue,
          type: 'bar'
        }
      ]
    };
    return { pieOption, barOption }
  }
  // 解构两个option
  const { pieOption, barOption } = getoption()
  return (
    <div className="monthlyBill">
      <NavBar className="nav" backArrow={false}>
        年度收支
      </NavBar>
      <div className="content">
        <div className="header">
          {/* 时间切换区域 */}
          <div className="date" onClick={() => setDataVisible(true)}>
            <span className="text">
              {currentDate}年账单
            </span>
            {/* 思路：根据当前弹框打开的状态控制expand类名是否存在 */}
            <span className={classNames('arrow', dataVisible && 'expand')}></span>
          </div>
          {/* 统计区域 */}
          <div className='twoLineOverview'>
            <div className="item">
              <span className="money">{monthResult.pay.toFixed(2)}</span>
              <span className="type">支出</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.income.toFixed(2)}</span>
              <span className="type">收入</span>
            </div>
            <div className="item">
              <span className="money">{monthResult.total.toFixed(2)}</span>
              <span className="type">结余</span>
            </div>
          </div>
          {/* 时间选择器 */}
          <DatePicker
            className="kaDate"
            title="记账日期"
            precision="year"
            visible={dataVisible}
            // onCancel={() => setDataVisible(false)}
            onConfirm={onConfirm}
            onClose={() => setDataVisible(false)}
            max={new Date()}
          />
        </div>
        {/* 图表显示区 */}
        <Tabs
          onChange={key => {
            return setClassType(key)
          }}>
          <Tabs.Tab
            className='tabs'
            title='支出'
            key='pay'
          >
            <ReactEcharts option={pieOption} />
            <ReactEcharts option={barOption} />
          </Tabs.Tab>
          <Tabs.Tab
            title='收入'
            key='income'
          >
            <ReactEcharts option={pieOption} />
            <ReactEcharts option={barOption} />
          </Tabs.Tab>
        </Tabs>
      </div>
    </div >
  )
}

export default Year